package com.ruoyi.web.controller.laiqianba.channel;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.channel.service.IChannelCountInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.db.domain.ChannelCountInfo;
import com.ruoyi.db.domain.MemberBaseInfo;
import com.ruoyi.db.domain.MemberSourceInfo;
import com.ruoyi.member.service.IMemberBaseInfoService;
import com.ruoyi.member.service.IMemberSourceInfoService;
import com.ruoyi.web.wrapper.ChannelBaseInfoWrapper;
import com.ruoyi.web.wrapper.ChannelCountInfoWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 渠道统计信息Controller
 *
 * @author ruoyi
 * @date 2023-09-01
 */
@RestController
@RequestMapping("/channel/countInfo")
public class ChannelCountInfoController extends BaseController {
    @Autowired
    private IChannelCountInfoService channelCountInfoService;

    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;

    @Autowired
    private IMemberSourceInfoService memberSourceInfoService;


    /**
     * 查询渠道统计信息列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(ChannelCountInfo channelCountInfo) {

//
//        if (!SecurityUtils.loginUserIsAdmin()) {
//            channelCountInfo.setOwnerId(SecurityUtils.getUserId());
//        }

        List<Map<String, Object>> list = channelCountInfoService.selectChannelCountInfoMapList(channelCountInfo);
        if (list == null || list.isEmpty()) {
            return getDataTable(list);
        }

        list = new ChannelCountInfoWrapper(list).wrap();
        BigDecimal totalUvCost = BigDecimal.ZERO;
        for (Map<String, Object> item : list) {
            Object uvCostObj = item.get("uvCost");
            if (uvCostObj != null) {
                BigDecimal uvCost = new BigDecimal(uvCostObj.toString());
                totalUvCost = totalUvCost.add(uvCost);
            }
        }

        BigDecimal totalWuYongValue = BigDecimal.ZERO;
        for (Map<String, Object> item : list) {
            Object wuYongValue = item.get("wuYongValue");
            if (wuYongValue != null) {
                BigDecimal uvCost = new BigDecimal(wuYongValue.toString());
                totalWuYongValue = totalWuYongValue.add(uvCost);
            }
        }


        // 提取 channelCode 为 baidu001 和 baidu002 的项
//        List<Map<String, Object>> baidu001List = new ArrayList<>();
//        List<Map<String, Object>> baidu002List = new ArrayList<>();
//        for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext(); ) {
//            Map<String, Object> item = iterator.next();
//            if ("baidu001".equals(item.get("channelCode"))) {
//                baidu001List.add(item); // 将 baidu001 项加入新的列表
//                iterator.remove(); // 从原列表中移除 baidu001 项
//            } else if ("baidu002".equals(item.get("channelCode"))) {
//                baidu002List.add(item); // 将 baidu002 项加入新的列表
//                iterator.remove(); // 从原列表中移除 baidu002 项
//            }
//        }

        // 排序，先按日期倒序，再按 uvCost 和 regCost 的和倒序
        list.sort(Comparator.comparing((Map<String, Object> item) -> {
                    String dateInfoStr = (String) item.get("dateInfo");
                    return dateInfoStr != null ? LocalDate.parse(dateInfoStr) : LocalDate.MIN;
                }).reversed()
                .thenComparing(item -> {
                    // 获取 uvCost 和 regCost 的和
                    BigDecimal uvCost = item.get("uvCost") != null ?
                            new BigDecimal(item.get("uvCost").toString()) :
                            BigDecimal.ZERO;
                    BigDecimal regCost = item.get("regCost") != null ?
                            new BigDecimal(item.get("regCost").toString()) :
                            BigDecimal.ZERO;
                    return uvCost.add(regCost).negate();
                }));

//        baidu001List = new ChannelCountInfoWrapper(baidu001List).wrap();
//        baidu002List = new ChannelCountInfoWrapper(baidu002List).wrap();
//
//        // 分别对 baidu001 和 baidu002 的项按 dateInfo 进行排序
//        baidu001List.sort(Comparator.comparing((Map<String, Object> item) -> {
//            String dateInfoStr = (String) item.get("dateInfo");
//            return dateInfoStr != null ? LocalDate.parse(dateInfoStr) : LocalDate.MIN;
//        }).reversed());
//
//        baidu002List.sort(Comparator.comparing((Map<String, Object> item) -> {
//            String dateInfoStr = (String) item.get("dateInfo");
//            return dateInfoStr != null ? LocalDate.parse(dateInfoStr) : LocalDate.MIN;
//        }).reversed());
//
        Map<String, Object> AllUvCount = channelCountInfoService.selectChannelCountInfoAllMapList(channelCountInfo);
        AllUvCount.put("uvCost", totalUvCost);
        AllUvCount.put("wuYongValue", totalWuYongValue);
        AllUvCount = new ChannelCountInfoWrapper(AllUvCount).wrap();

        list.add(0, AllUvCount);
//
//        // 如果存在 baidu001 和 baidu002 数据，则按顺序插入到总计数据之后
//        list.addAll(1, baidu001List);
//        list.addAll(1 + baidu001List.size(), baidu002List);


        // 将 flowRateType 等于 APIS 的项排到最后
//        list.sort(Comparator.comparing((Map<String, Object> item) -> "APIS".equals(item.get("flowRateType"))));

        return getDataTable(list);
    }


    /**
     * 导出渠道统计信息列表
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:export')")
    @Log(title = "渠道统计信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ChannelCountInfo channelCountInfo) {
        List<ChannelCountInfo> list = channelCountInfoService.selectChannelCountInfoList(channelCountInfo);
        ExcelUtil<ChannelCountInfo> util = new ExcelUtil<ChannelCountInfo>(ChannelCountInfo.class);
        util.exportExcel(response, list, "渠道统计信息数据");
    }

    /**
     * 获取渠道统计信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(channelCountInfoService.selectChannelCountInfoById(id));
    }

    /**
     * 新增渠道统计信息
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:add')")
    @Log(title = "渠道统计信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ChannelCountInfo channelCountInfo) {
        return toAjax(channelCountInfoService.insertChannelCountInfo(channelCountInfo));
    }

    /**
     * 修改渠道统计信息
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:edit')")
    @Log(title = "渠道统计信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ChannelCountInfo channelCountInfo) {
        return toAjax(channelCountInfoService.updateChannelCountInfo(channelCountInfo));
    }

    /**
     * 删除渠道统计信息
     */
    @PreAuthorize("@ss.hasPermi('channel:countInfo:remove')")
    @Log(title = "渠道统计信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(channelCountInfoService.deleteChannelCountInfoByIds(ids));
    }


    /**
     * 渠道统计
     */
    @GetMapping(value = "/count")
    public AjaxResult getInfo(ChannelCountInfo channelCountInfo) {
        //用户实名
        MemberBaseInfo memberBaseInfo = new MemberBaseInfo();
        memberBaseInfo.setChannelCode(channelCountInfo.getChannelCode());
        memberBaseInfo.setChannelName(channelCountInfo.getChannelName());
        memberBaseInfo.setDateInfo(channelCountInfo.getDateInfo());
        memberBaseInfo.setStartDateInfo(channelCountInfo.getStartDateInfo());
        memberBaseInfo.setEndDateInfo(channelCountInfo.getEndDateInfo());
        List<Map<String, Object>> authMember = memberBaseInfoService.selectMemberBaseInfoByChannelCode(memberBaseInfo);

        //芝麻
        MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
        memberSourceInfo.setChannelCode(channelCountInfo.getChannelCode());
        memberSourceInfo.setChannelName(channelCountInfo.getChannelName());
        memberSourceInfo.setDateInfo(channelCountInfo.getDateInfo());
        memberSourceInfo.setStartDateInfo(channelCountInfo.getStartDateInfo());
        memberSourceInfo.setEndDateInfo(channelCountInfo.getEndDateInfo());
        List<Map<String, Object>> zhiMaMember = memberSourceInfoService.selectMemberSourceInfoByChannelCode(memberSourceInfo);

        //年龄
        List<Map<String, Object>> ageMember = memberSourceInfoService.selectAgeByChannelCode(memberSourceInfo);


        //省份
        List<Map<String, Object>> provinceMember = memberSourceInfoService.selectProvinceByChannelCode(memberSourceInfo);


        JSONObject returnData = new JSONObject();
        returnData.put("authMemberData", authMember);
        returnData.put("zhiMaMemberData", zhiMaMember);
        returnData.put("ageMemberData", ageMember);
        returnData.put("provinceMemberData", provinceMember);

        return success(returnData);
    }

    @GetMapping("/getWeComCount")
    public TableDataInfo getWeComCount(ChannelCountInfo channelCountInfo) {
        startPage();
        List<Map<String, Object>> list = channelCountInfoService.getWeComCount(channelCountInfo);
        list = new ChannelBaseInfoWrapper(list).wrap();
        return getDataTable(list);
    }
}
